#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>

// 设置指定fd为非阻塞
void SetNonBlock(int fd)
{
    // 获取文件描述符标志
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        std::cout << "fcntl error" << std::endl;
        exit(0);
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    // 将stdin设置为非阻塞
    SetNonBlock(0);

    while(true)
    {
        char buff[1024];
        ssize_t ret = read(0, buff, sizeof(buff) - 1);
        if(ret > 0)
        {
            buff[ret] = 0;
            std::cout << "echo# " << buff << std::endl;
        }
        else if(ret == 0)
        {
            std::cout << "stdin end" << std::endl;
            break;
        }
        else 
        {
            if(errno == EWOULDBLOCK)
            {
                std::cout << "os的底层数据还没有就绪, errno: " << errno << std::endl;
            }
            else if(errno == EINTR)
            {  
                std::cout << "IO interrupted by signed, try again" << std::endl;
            }
            else
            {
                std::cout << "read error" << std::endl;
                break;
            }
        }

        sleep(1);
    }
    return 0;
}